package com.zb.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.client.SkuFeignClient;
import com.zb.dto.SkuDTO;
import com.zb.entity.TbOrderItemModel;
import com.zb.entity.TbOrderModel;
import com.zb.mapper.TbOrderMapper;
import com.zb.service.CartService;
import com.zb.service.TbOrderItemService;
import com.zb.service.TbOrderService;
import com.zb.vo.BuyGoodsVO;
import com.zb.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @ClassName TbOrderServiceImpl
 * @Description 服务接口实现
 * @Author xm
 * @Date 2024/11/07 09:05
 **/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrderModel>implements TbOrderService {
	@Autowired(required = false)
	private TbOrderItemService tbOrderItemService;

	@Autowired(required = false)
	private SkuFeignClient skuFeignClient;
	@Autowired
	private CartService cartService;
	@Autowired
	private RedisTemplate redisTemplate;



	@Override
	public Boolean createOrder(OrderVO orderVO	) {
		List<TbOrderItemModel> itemList = cartService.select(orderVO.getSkuIds(), orderVO.getUsername());
		TbOrderModel orderModel = new TbOrderModel();
		BeanUtils.copyProperties(orderVO,orderModel);
//		orderModel.setId(UUID.randomUUID().toString());
		orderModel.setId(IdWorker.getIdStr());
		Integer totalMoney = 0;
		Integer totalNum = 0;
		for (TbOrderItemModel tbOrderItemModel : itemList) {
			//远程调用商品信息
			SkuDTO skuDTO = skuFeignClient.info(tbOrderItemModel.getSkuId());
			totalMoney += skuDTO.getPrice() * tbOrderItemModel.getNum();
			totalNum += tbOrderItemModel.getNum();

			//添加订单详情

			tbOrderItemModel.setId(IdWorker.getIdStr());
			tbOrderItemModel.setSkuId(skuDTO.getId());
			tbOrderItemModel.setOrderId(orderModel.getId());
			tbOrderItemModel.setName(skuDTO.getName());
			tbOrderItemModel.setPrice(skuDTO.getPrice());
			tbOrderItemModel.setMoney(skuDTO.getPrice() * tbOrderItemModel.getNum());
			tbOrderItemModel.setImage(skuDTO.getImage());
			tbOrderItemModel.setWeight(skuDTO.getWeight());
			tbOrderItemService.save(tbOrderItemModel);
			//远程调用修改商品库存
			skuFeignClient.update(skuDTO.getId(), tbOrderItemModel.getNum());
		}
		orderModel.setTotalMoney(totalMoney);
		orderModel.setTotalNum(totalNum);
		boolean save = this.save(orderModel);
		//删除购物车
		redisTemplate.boundHashOps("cart"+orderVO.getUsername()).delete(orderVO.getSkuIds());
		return save;
	}
}
